import { createStore } from "vuex";
import axios from "axios";

export default createStore({
  // 定义初始状态
  state: () => ({
    coffees: [], // 存储咖啡数据的数组
    cartQuantities: {},
  }),

  // 定义修改状态的方法
  mutations: {
    // 设置咖啡数据
    setCoffees(state, coffees) {
      const coffeesWithQuantity = coffees.map((category) => ({
        ...category,
        details: category.details.map((detail) => ({
          ...detail,
          quantity: state.cartQuantities[detail.id] || 0,
        })),
      }));
      state.coffees = coffeesWithQuantity;
    },

    // 添加商品到购物车
    addToCart(state, detailId) {
      // 查找对应的咖啡详情
      const detail = state.coffees
        .find((element) =>
          element.details.some((detail) => detail.id === detailId)
        )
        ?.details.find((detail) => detail.id === detailId);

      if (detail) {
        // 初始化数量并增加
        if (!detail.quantity) {
          detail.quantity = 0;
        }
        detail.quantity++;
        state.cartQuantities[detailId] = detail.quantity;
      }
    },

    // 从购物车移除商品
    removeFromCart(state, detailId) {
      const detail = state.coffees
        .find((element) =>
          element.details.some((detail) => detail.id === detailId)
        )
        ?.details.find((detail) => detail.id === detailId);

      if (detail && detail.quantity > 0) {
        detail.quantity--;
        state.cartQuantities[detailId] = detail.quantity;
      }
    },
  },

  // 定义异步操作和复杂逻辑
  actions: {
    // 从服务器获取咖啡数据
    async fetchCoffees({ commit }) {
      try {
        const response = await axios.get("http://localhost:3004/coffees");
        commit("setCoffees", response.data);
      } catch (error) {
        console.error("Error fetching coffees:", error);
      }
    },

    // 购物车操作的 actions
    addToCart({ commit }, detailId) {
      commit("addToCart", detailId);
    },
    removeFromCart({ commit }, detailId) {
      commit("removeFromCart", detailId);
    },

    // 计算购物车总金额
    calculateTotalAmount({ state }) {
      let total = 0;
      state.coffees.forEach((category) => {
        category.details.forEach((detail) => {
          if (detail.quantity > 0) {
            total += parseFloat((detail.quantity * detail.price).toFixed(2));
          }
        });
      });
      return total;
    },

    // 计算购物车商品总数
    calculateTotal({ state }) {
      let total = 0;
      state.coffees.forEach((category) => {
        category.details.forEach((detail) => {
          if (detail.quantity > 0) {
            total += parseFloat(detail.quantity.toFixed(2));
          }
        });
      });
      return total;
    },
  },

  // 定义获取状态的计算属性
  getters: {
    // 根据ID查找商品详情
    findDetailById: (state) => (detailId) => {
      let found = null;
      state.coffees.forEach((element) => {
        const detail = element.details.find((detail) => detail.id === detailId);
        if (detail) found = detail;
      });
      return found;
    },
  },
});
